import Vue from 'vue'
import Vuex from 'vuex'
import {setStorageSync} from "../api/wechat";

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    token: wx.getStorageSync('token') == "" ? "" : wx.getStorageSync('token'),
    error: null,
    isLogin:wx.getStorageSync('isLogin') == "" ? false: wx.getStorageSync('isLogin'),
    showLoginDailog:wx.getStorageSync('showLoginDailog') == "" ? false:wx.getStorageSync('showLoginDailog'),
    userInfo:wx.getStorageSync('user') == "" ? "" : wx.getStorageSync('user'),
  },
  mutations: {
    setError: (state, message) => {
      if (message) {
        state.error = { message }
      } else {
        state.error = null
      }
    },
    setIsLogin:(state,isLogin) => {
      state.isLogin = isLogin;
    },
    refreshToken : (state, token) => {
      state.token = token;
    },
    setShowLoginDailog:(state, show) => {
      state.showLoginDailog = show;
    },
    setUserInfo:( state , user) =>{
      state.userInfo = user;
    }
  },
  actions: {
    refreshToken ({commit}, token) {
      return new Promise(function (resolve, reject) {
        console.log("actions,refreshToken",token);
        setStorageSync('token', token);
        commit('refreshToken', token);
      })
    },
    showLoginDialog ({commit}, show) {
      return new Promise(function (resolve, reject) {
        setStorageSync('showLoginDailog',show);
        commit('setShowLoginDailog', show);
      })
    },
    userInfo ({commit}, user){
      return new Promise(function (resolve, reject) {
        setStorageSync('user',user);
        setStorageSync('user.user_id',user.id);
        commit('setUserInfo', user);
      })
    },
    isLogin ({commit}, isLogin){
      return new Promise(function (resolve, reject) {
        setStorageSync('isLogin',isLogin);
        commit('setIsLogin', isLogin);
      })
    },
  },
  getters:{
    isLogin(state){
      return state.isLogin;
    }
  }
})

export default store
